﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;

namespace DeltaPlcSystem
{
    public class PublicClass
    {    
        public static string Post(string url, string jsonParam)
        {
            string result = "";//返回结果
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.ServicePoint.Expect100Continue = false;
                request.ServicePoint.UseNagleAlgorithm = false;
                request.ServicePoint.ConnectionLimit = int.MaxValue;
                request.AllowWriteStreamBuffering = false;
                request.Proxy = null;
                //添加Authorization到HTTP头
                byte[] payload = Encoding.UTF8.GetBytes(jsonParam);
                request.ContentLength = payload.Length;
                reqStream = request.GetRequestStream();
                reqStream.Write(payload, 0, payload.Length);
                reqStream.Close();
                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception ex)
            {
                
            }
        
            return result;
        }

        public static string ToBinary(ushort num)
        {

            string tempV = Convert.ToString(num, 2);


            for (int i = 1; i < 10; i++)
            {
                if (tempV.Length < 4 * i && tempV.Length % 4 != 0) 
                {
                    tempV = tempV.PadLeft(4 * i, '0');
                    break;
                }
            }

            return tempV;
        }

        public static string NetLog(int mode,string logStr)
        {
            string tempStr=string.Empty;
            try
            {
                if (mode == 0)
                {
                    tempStr=DateTime.Now.ToString() + " NORMAL：--------------------------" + logStr + "--------------------------行号：";
                }
                else if (mode == 1)
                {
                    tempStr = DateTime.Now.ToString() + " ERROR：" + logStr + "-------------行号：";
                }
                else
                {
                    tempStr = DateTime.Now.ToString() + " NORMAL：" + logStr + "-------------行号：";
                }

                return tempStr;
            }
            catch { return tempStr; }
        }

        /// <summary>
        /// 将文件大小(字节)统一转换为M为单位
        /// </summary>
        /// <param name="size">文件字节</param>
        /// <returns>返回转换后的字符串</returns>
        public static double ConvertFileSizeToM(long size)
        {
            double result = 0;
            if (size > 0)
            {
                result = Math.Round(Convert.ToDouble(size / 1024d / 1024), 2);
            }
            return result;
        }

        /// <summary>
        /// 设置开机自启动
        /// </summary>
        /// <param name="keyName">目标名</param>
        /// <param name="filePath">exe路径</param>
        /// <param name="AddOrCancel">启动或取消</param>
        /// <returns></returns>
        public static bool SetMeStart(bool onOff)
        {
            bool isOk = false;
            string appName = Process.GetCurrentProcess().MainModule.ModuleName;
            string appPath = Process.GetCurrentProcess().MainModule.FileName;
            isOk = SetAutoStart(onOff, appName, appPath);
            return isOk;
        }
        /// <summary>
        /// 将应用程序设为或不设为开机启动
        /// </summary>
        /// <param name="onOff">自启开关</param>
        /// <param name="appName">应用程序名</param>
        /// <param name="appPath">应用程序完全路径</param>
        public static bool SetAutoStart(bool onOff, string appName, string appPath)
        {
            bool isOk = true;
            //如果从没有设为开机启动设置到要设为开机启动
            if (!IsExistKey(appName) && onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            //如果从设为开机启动设置到不要设为开机启动
            else if (IsExistKey(appName) && !onOff)
            {
                isOk = SelfRunning(onOff, appName, @appPath);
            }
            else 
                isOk = false;

            return isOk;
        }



    
        /// <summary>
        /// 判断注册键值对是否存在，即是否处于开机启动状态
        /// </summary>
        /// <param name="keyName">键值名</param>
        /// <returns></returns>
        private static bool IsExistKey(string keyName)
        {
            try
            {
                bool _exist = false;
                RegistryKey local = Registry.LocalMachine;
                RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (runs == null)
                {
                    RegistryKey key2 = local.CreateSubKey("SOFTWARE");
                    RegistryKey key3 = key2.CreateSubKey("Microsoft");
                    RegistryKey key4 = key3.CreateSubKey("Windows");
                    RegistryKey key5 = key4.CreateSubKey("CurrentVersion");
                    RegistryKey key6 = key5.CreateSubKey("Run");
                    runs = key6;
                }
                string[] runsName = runs.GetValueNames();
                foreach (string strName in runsName)
                {
                    if (strName.ToUpper() == keyName.ToUpper())
                    {
                        _exist = true;
                        return _exist;
                    }
                }
                return _exist;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 写入或删除注册表键值对,即设为开机启动或开机不启动
        /// </summary>
        /// <param name="isStart">是否开机启动</param>
        /// <param name="exeName">应用程序名</param>
        /// <param name="path">应用程序路径带程序名</param>
        /// <returns></returns>
        private static bool SelfRunning(bool isStart, string exeName, string path)
        {
            try
            {
                RegistryKey local = Registry.LocalMachine;
                RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (key == null)
                {
                    local.CreateSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");
                }
                //若开机自启动则添加键值对
                if (isStart)
                {
                    key.SetValue(exeName, path);
                    key.Close();
                }
                else//否则删除键值对
                {
                    string[] keyNames = key.GetValueNames();
                    foreach (string keyName in keyNames)
                    {
                        if (keyName.ToUpper() == exeName.ToUpper())
                        {
                            key.DeleteValue(exeName);
                            key.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string ss = ex.Message;
                return false;
                //throw;
            }
            return true;
        }

    }


    public class JsonData
    {     
        public string interfaceID = string.Empty;      
        public int status;
        public string statusCode = string.Empty;
        public int passQty;
        public int failQty ;
        public int errorCnt  ;
        public double errorTimes;
        public double cycleTime;
        public double runningTime;
        public double waitingTime;
        public int selfCheck;
        public int inputQty;
        public string barcode = string.Empty;
        public string model = string.Empty;

        public List<paramLists> paramList=new List<paramLists>();

        public JsonData(string ctm, string ctq) 
        {
            paramLists pl1 = new paramLists();
            pl1.paramCode = "CT_M";
            pl1.paramValue = ctm;

            paramLists pl2 = new paramLists();
            pl2.paramCode = "CT_Q";
            pl2.paramValue = ctq;

            paramList.Add(pl1);
            paramList.Add(pl2);
        }   
        

        //public string CT_Q = string.Empty;
        //public string CT_M = string.Empty;
    }


    public class paramLists
    {
        public string paramCode=string.Empty;
        public string paramValue=string.Empty;
    }
}
